package com.android.kmlmrg.services.rest.method;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpStatus;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Application;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;

import com.android.kmlmrg.R;
import com.android.kmlmrg.event.RestUpdateUserEvent;
import com.android.kmlmrg.listener.custom.RestUpdateUserListener;
import com.android.kmlmrg.model.User;
import com.android.kmlmrg.services.ServiceController;
import com.android.kmlmrg.views.ViewContact;

public class UpdateUser extends AsyncTask<Void, Integer, String> {


	/**LOG**/
	private static final  String LOG_TAG = UpdateUser.class.getSimpleName();

	private User user;

	private static final String JSON_FIELD_STATUS = "status";

	private static final String METHODE_NAME = "/updateUser";

	private Application application;

	private int code;

	private static  ArrayList<RestUpdateUserListener> listeners = new ArrayList<RestUpdateUserListener>();

	public UpdateUser(Application pApplication , User pUser) {
		application = pApplication;
		Log.i(LOG_TAG, "START - Constructeur UpdateUser (Application pApplication, User pUser) ");
		user = pUser;
		
		Log.i(LOG_TAG, "END - Constructeur UpdateUser ");
	}

	

	@Override
	protected String doInBackground(Void... params) {
		try {
			Log.i(LOG_TAG, "START - doInBackground ");
			String vUrl = this.application.getString(R.string.user_endpoint) + METHODE_NAME ;

				
			String message = user.toDataForUpdate();

	
			HttpURLConnection httpcon = (HttpURLConnection) ((new URL(vUrl).openConnection()));

			httpcon.setRequestProperty("Content-Type", "application/json");
			httpcon.setRequestProperty("Accept", "application/json");
			httpcon.setRequestMethod("POST");

			httpcon.setDoInput(true);
			httpcon.setDoOutput(true);
			httpcon.setFixedLengthStreamingMode(message.getBytes().length);
			httpcon.connect();


			OutputStream os = new BufferedOutputStream(httpcon.getOutputStream());
			os.write(message.getBytes());
			//clean up
			os.flush();


			// this will be useful so that you can show a typical 0-100% progress bar
			int fileLength = httpcon.getContentLength();

			code = httpcon.getResponseCode();


			InputStream input = httpcon.getInputStream();
			BufferedReader r = new BufferedReader(new InputStreamReader(input));
			StringBuilder total = new StringBuilder();
			String line;
			while ((line = r.readLine()) != null) {
				total.append(line);
			}
			os.flush();
			os.close();
			input.close();	
			Log.i(LOG_TAG, "END - doInBackground ");
			return total.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}


	@Override
	protected void onPostExecute(String result) {
		Log.i(LOG_TAG, "START - onPostExecute(String result)");
		Log.i(LOG_TAG, "RESPONSE : " + result);

		try {
			if (code == HttpStatus.SC_OK) {
				JSONObject vJsonObject;
				vJsonObject = new JSONObject(result);
				User vUser = getOriginalUserById(user.getIdentifiant());
				
				vUser.setCodePostal(user.getCodePostal());
				vUser.setDateNaissance(user.getDateNaissance());
				vUser.setEmail(user.getEmail());
				vUser.setNom(user.getNom());
				vUser.setNumeroRue(user.getNumeroRue());
				vUser.setNomRue(user.getNomRue());
				vUser.setPays(user.getPays());
				vUser.setPrenom(user.getPrenom());
				vUser.setTel(user.getTel());
				vUser.setVille(user.getVille());
				
				
				
				RestUpdateUserEvent vEvent = new RestUpdateUserEvent(this, false, vUser);
				String vStatus = (String) vJsonObject.get(JSON_FIELD_STATUS);
				if (vStatus.equalsIgnoreCase("true") && vUser != null ) {
					vEvent = new RestUpdateUserEvent(this, true, vUser);
				} 
				fireEvent(vEvent);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		Log.i(LOG_TAG, "END - onPostExecute");
		super.onPostExecute(result);
	}



	private void fireEvent( RestUpdateUserEvent pEvent ){		
		for(RestUpdateUserListener listener : listeners){
			listener.resultGetUserRequest( pEvent );
		}
	}

	public static void addListener ( RestUpdateUserListener pListener ){
		listeners.add(pListener);
	}

	public static void removeListener( RestUpdateUserListener pListener ){
		listeners.remove(pListener);
	}

 private User getOriginalUserById ( String id ) {
	
		List<User> vListUser =ServiceController.getInstance().getUsers().getList();
		
		for ( User userX : vListUser ){
			if (userX.getIdentifiant().equalsIgnoreCase(id ) ) {
				return userX;
			}
		}
		return null;
 }


}
